package com.woniu.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class RabbitMQConfig {
    //正常交换机
    public static final String NORMAL_EXCHANGE_NAME = "延时交换机";
    //正常队列
    public static final String NORMAL_QUEUE_NAME = "延时队列";
    //正常路由key
    public static final String NORMAL_ROUTING_KEY = "normal_routing_key";
    //死信交换机
    public static final String DEATH_EXCHANGE_NAME = "死信交换机";
    //死信队列
    public static final String DEATH_QUEUE_NAME = "死信队列";
    //死信路由key
    public static final String DEATH_ROUTING_KEY = "death_routing_key";

    //声明普通交换机
    @Bean("normal_exchange")
    public Exchange normalExchange() {
        return ExchangeBuilder.directExchange(NORMAL_EXCHANGE_NAME).durable(true).build();
    }

    //声明普通队列
    @Bean("normal_queue")
    public Queue normalQueue() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", 120 * 1000); // 2分钟
        map.put("x-dead-letter-exchange", DEATH_EXCHANGE_NAME);
        map.put("x-dead-letter-routing-key", DEATH_ROUTING_KEY);

        return QueueBuilder.durable(NORMAL_QUEUE_NAME).withArguments(map).build();
    }

    //声明死信交换机
    @Bean("death_exchange")
    public Exchange deathExchange() {
        return ExchangeBuilder.directExchange(DEATH_EXCHANGE_NAME).durable(true).build();
    }

    //声明死信队列
    @Bean("death_queue")
    public Queue deathQueue() {
        return QueueBuilder.durable(DEATH_QUEUE_NAME).build();
    }

    //把正常队列绑定到正常交换机
    @Bean
    public Binding bindingNormal(@Qualifier("normal_queue") Queue queue, @Qualifier("normal_exchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(NORMAL_ROUTING_KEY).noargs();
    }

    //把死信队列绑定到死信交换机
    @Bean
    public Binding bindingDeath(@Qualifier("death_queue") Queue queue, @Qualifier("death_exchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with(DEATH_ROUTING_KEY).noargs();
    }
}
